package com.example.camera__demo;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class CommonCamera extends Activity implements OnClickListener {
	ImageView imageView;
	Button button;
	private static final int IMAGE_REQUEST_CODE = 200;
	private File currentFile = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_common);
		initView();
	}

	private void initView() {
		// TODO Auto-generated method stub
		imageView = (ImageView) findViewById(R.id.imageView1);
		button = (Button) findViewById(R.id.button1);
		button.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		File dir = new File(Environment.getExternalStorageDirectory(),
				"cameraphoto");
		if (!dir.exists()) {
			dir.mkdirs();
		}
		
		currentFile = new File(dir, System.currentTimeMillis() + ".jpg");
		if (!currentFile.exists()) {
			try {
				currentFile.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		in.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(currentFile));
		startActivityForResult(in, IMAGE_REQUEST_CODE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d("TAG", requestCode + "\n" + resultCode);
		if (requestCode == IMAGE_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				imageView.setImageURI(Uri.fromFile(currentFile));
			}else{
				currentFile.delete();
			}
		}
	}
}
